<template>
    <view>
        <view v-if="skuShowKey">
            <azNavbar navtype="default" isScroll :bgColor="navBgColor">
                <template v-slot:header>
                    <view class="header">
                        <view class="padding-lr-sm flex align-center" style="width: 100%">
                            <view @click="back()" class="icon">
                                <view class="cuIcon-back text-grey"></view>
                            </view>
                            <!-- #ifdef MP-WEIXIN -->
                            <view v-if="option > 0" class="margin-left-base text-lg">商品详情</view>
                            <!-- #endif -->
                            <!-- #ifndef MP-WEIXIN -->
                            <view v-if="option > 0" class="text-center text-lg title">商品详情</view>
                            <!-- #endif -->
                        </view>
                    </view>
                </template>
            </azNavbar>

            <!-- 轮播 -->
            <view :style="{ marginTop: `-${systemStore.navHeight}px` }">
                <goodsSwiper v-model="swipers" :ratio="1" indicatorDots />
            </view>

            <!-- 信息 -->
            <view class="margin-base padding-base bg-white radius-2xl">
                <view class="flex align-center justify-between">
                    <view class="flex align-center">
                        <view class="text-red text-bold margin-right-sm">
                            <text>￥</text>
                            <text class="text-2xl">{{ goods.price }}</text>
                        </view>
                        <view class="text-grey text-line">
                            <text>￥</text>
                            <text>{{ goods.tprice }}</text>
                        </view>
                    </view>
                    <view @click="shareRef?.open()" class="icon-fenxiang text-grey text-xl"></view>
                </view>
                <view class="margin-top-sm text-xl text-bold">{{ goods.title }}</view>
                <view class="margin-top-lg flex align-center justify-between">
                    <view class="text-grey">销量：{{ goods.sales }}</view>
                    <view>
                        <text v-if="!memberStore.userInfo.username" @click="goPage('/pages/user/login')" class="cuIcon-like text-grey text-xl"></text>
                        <text
                            v-else
                            @click="collect"
                            class="text-xl"
                            :class="shoucang === 1 ? 'cuIcon-likefill text-red' : 'cuIcon-like text-grey'"
                        ></text>
                    </view>
                </view>
            </view>

            <!-- 服务 -->
            <view class="margin-base padding-base bg-white radius-2xl">
                <view @click="popupBottomRef?.open()" class="flex align-center justify-between">
                    <view style="width: 100rpx" class="text-grey text-bold">配送</view>
                    <view style="flex: 1" class="flex align-center justify-between">
                        <view>付款后24小时内发货</view>
                        <view class="cuIcon-right text-lg text-grey"></view>
                    </view>
                </view>
                <view @click="popupBottomRef?.open()" class="flex align-center justify-between margin-top-base">
                    <view style="width: 100rpx" class="text-grey text-bold">保障</view>
                    <view style="flex: 1" class="flex align-center justify-between">
                        <view>支持7天内无理由退换货</view>
                        <view class="cuIcon-right text-lg text-grey"></view>
                    </view>
                </view>
            </view>

            <!-- 评价 -->
            <view class="margin-base padding-base bg-white radius-2xl flex align-center justify-between">
                <view class="text-lg text-bold">商品评价</view>
                <view class="flex align-center">
                    <view class="margin-right-xs">全部</view>
                    <view class="cuIcon-right text-lg text-grey"></view>
                </view>
            </view>

            <!-- 店铺 -->
            <view class="margin-base padding-base bg-white radius-2xl">
                <storeGoodsList ref="storeGoodsListRef" :data="goods" />
            </view>

            <!-- 商品详情 -->
            <view v-if="content" class="margin-base padding-base bg-white radius-2xl">
                <view class="text-lg text-bold margin-bottom-base">商品详情</view>
                <view>
                    <rich-text :nodes="content"></rich-text>
                </view>
            </view>

            <!-- 底部操作 -->
            <view class="cu-bar tabbar"></view>
            <view class="cu-bar tabbar foot bg-white padding-lr-base">
                <view class="bar-inner">
                    <view class="bar-left">
                        <view class="item text-grey">
                            <view class="cuIcon-shop text-xl"></view>
                            <view class="text-sm">店铺</view>
                        </view>
                        <view @click="baseCall(goods?.company.telephone)" class="item text-grey">
                            <view class="cuIcon-service text-xl"></view>
                            <view class="text-sm">客服</view>
                        </view>
                        <view @click="goPage('/pages/index/cart')" class="item text-grey">
                            <view class="cuIcon-cart text-xl"></view>
                            <view class="text-sm">购物车</view>
                        </view>
                    </view>
                    <view class="bar-right">
                        <button @click="openSkuPopup('cart')" class="cu-btn round bg-orange text-sm">加入购物车</button>
                        <button @click="openSkuPopup('buy')" class="cu-btn round bg-main text-sm">立即购买</button>
                    </view>
                </view>
            </view>

            <!-- 服务弹窗 -->
            <popupBottom ref="popupBottomRef" title="服务说明" height="25vh">
                <template v-slot:content>
                    <view class="text-grey" style="line-height: 1.5"
                        >该商品支持签收起7天内售后，如在7天内发现质量问题，您可联系客服售后解决:如签收起7天内您购买的商品包装未打开不影响二次销售，您可以申请无理由退货，特别说明:
                        如您使用无理由退货，需支付运费5元
                    </view>
                </template>
            </popupBottom>

            <!-- sku弹窗 -->
            <goodsSkuPopup v-if="skuShowKey" ref="goodsSkuPopupRef" :goods="goods" :mode="openMode" @add-cart="addCart" @buy="buy" />
            <!-- 分享 -->
            <share ref="shareRef" />
        </view>
        <loading v-else></loading>
    </view>
</template>

<script lang="ts" setup>
import goodsSwiper from "@/components/goods/goods-swiper.vue";
import azNavbar from "@/components/common/az-navbar.vue";
import popupBottom from "@/components/common/popup-bottom.vue";
import storeGoodsList from "@/components/goods/store-goods-list.vue";
import goodsSkuPopup from "@/components/goods/goods-sku-popup.vue";
import share from "@/components/common/share.vue";
import loading from "@/components/common/loading.vue";

import { ref } from "vue";
import type { shareOption } from "@/types/global";
import { back, goPage, baseCall } from "@/utils/index";
import { useTask } from "@/utils/message";
import { productdetailApi, shoucangApi, shoucangcancelApi } from "@/api/goods";
import { onLoad, onPageScroll, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { useMemberStore } from "@/store/module/member";
import { useSystemStore } from "@/store/module/system";
import { useCartStore } from "@/store/module/cart";

const systemStore = useSystemStore();
const memberStore = useMemberStore();
const cartStore = useCartStore();
const popupBottomRef = ref<InstanceType<typeof popupBottom>>();
const goodsSkuPopupRef = ref<InstanceType<typeof goodsSkuPopup>>();
const storeGoodsListRef = ref<InstanceType<typeof storeGoodsList>>();
const shareRef = ref<InstanceType<typeof share>>();
const goods = ref<AnyObject>({}); //商品数据
const goodsid = ref<string>(""); //商品id
const swipers = ref<any[]>([]); // 轮播图
const content = ref<string>(""); // 商品数据
const option = ref<number>(0); // 导航栏透明度
const navBgColor = ref<string>("rgba(255,255,255,0)"); //导航栏背景色
const shoucang = ref<number>(0); // 是否收藏
const openMode = ref<"buy" | "cart">("buy");
const skuShowKey = ref<boolean>(false);

const openSkuPopup = (mode: "buy" | "cart") => {
    openMode.value = mode;
    goodsSkuPopupRef.value?.open();
};

// 获取详情
const getGoodsDetail = async () => {
    const res: AnyObject = await productdetailApi({
        itemid: goodsid.value,
        userid: memberStore.userInfo.userid || undefined,
        username: memberStore.userInfo.username || undefined
    });
    if (res.code == 200) {
        goods.value = res.data;
        shoucang.value = goods.value.shoucang;
        storeGoodsListRef.value?.getList(goods.value);
        getSwipres(goods.value);
        getGoodsContent(goods.value);
        // 渲染页面
        skuShowKey.value = true;
    } else {
        useTask(res.msg);
        back();
    }
};

// 详情内容
const getGoodsContent = (goods: AnyObject) => {
    if (goods?.content?.content) {
        let data = goods?.content?.content;
        data = data.replace(/style=""/g, "");
        data = data.replace(/<img/g, "<img style='max-width:100%;height:auto;float:left;'");
        data = data.replace(/<span/g, "<span style='font-size: 14px !important;width:100%;'");
        content.value = data;
    } else {
        content.value = "";
    }
};

// 集合轮播图
const getSwipres = (goods: AnyObject) => {
    if (skuShowKey.value) return;
    if (goods.thumb) {
        swipers.value.push(goods.thumb);
    }
    if (goods.thumb1) {
        swipers.value.push(goods.thumb1);
    }
    if (goods.thumb2) {
        swipers.value.push(goods.thumb2);
    }
    if (goods.thumb3) {
        swipers.value.push(goods.thumb3);
    }
    if (goods.thumb4) {
        swipers.value.push(goods.thumb4);
    }
    if (goods.thumb5) {
        swipers.value.push(goods.thumb5);
    }
    if (goods.thumb6) {
        swipers.value.push(goods.thumb6);
    }
    if (goods.thumb7) {
        swipers.value.push(goods.thumb7);
    }
    if (goods.thumb8) {
        swipers.value.push(goods.thumb8);
    }
};

// 收藏
const collect = async () => {
    const params: AnyObject = {
        itemid: goodsid.value,
        userid: memberStore.userInfo.userid,
        mid: 23
    };
    let res: AnyObject = {};

    if (shoucang.value == 1) {
        res = await shoucangcancelApi(params);
    } else {
        res = await shoucangApi(params);
    }
    if (res.code == 200) {
        getGoodsDetail();
    } else {
        useTask(res.msg);
    }
};

// 加入购物车
const addCart = (sku: AnyObject) => {
    cartStore.addCart({
        pid: sku.pid,
        sku_id: sku.id,
        num: sku.num
    });
};

// 购买
const buy = (sku: AnyObject) => {
    console.log(sku);
};

// 获取分享参数
const getShareOption = (): shareOption => {
    let title = goods.value.title;
    let imageUrl = goods.value.thumb;
    let path: string = `/pages/goods/goodsdetail?id=${goodsid.value}`;
    if (memberStore.userInfo.username) {
        path = `/pages/goods/goodsdetail?id=${goodsid.value}&username=${memberStore?.userInfo?.username}`;
    }
    return {
        title: title,
        imageUrl: imageUrl,
        path: path
    };
};

// 分享参数
onShareAppMessage(() => {
    const option = getShareOption();
    return option;
});
onShareTimeline(() => {
    const option = getShareOption();
    return option;
});

// 轮播图变色
onPageScroll((e: any) => {
    if (e.scrollTop > 0) {
        option.value = e.scrollTop / 100;
        navBgColor.value = `rgba(255,255,255,${option.value})`;
    } else {
        option.value = 0;
        navBgColor.value = "rgba(255,255,255,0)";
    }
});

onLoad((e: any) => {
    goodsid.value = e.id;
    getGoodsDetail();
});
</script>

<style scoped lang="scss">
.header {
    width: 100%;
}
.icon {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border: 1px solid #eee;
    opacity: 1 !important;
}

.title {
    width: 100%;
}

.bar-inner {
    width: 100%;
    display: grid;
    grid-template-columns: 2fr 3fr;
    gap: 50rpx;

    .bar-left {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
    }

    .bar-right {
        display: grid;
        grid-template-columns: 3fr 2fr;
        gap: 30rpx;
        align-items: center;
    }
}
</style>
